﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using mesoBoard.Data;
using mesoBoard.Data.Repositories;
using System.Web.Mvc.Html;
using Microsoft.Web.Mvc;
using System.Data;
using System.Reflection;
using mesoBoard.Common;

namespace mesoBoard.Web.Helpers
{
    public static partial class mesoBoardHtmlHelpers
    {
        //
        // CAPTCHA code taken from "Pro ASP.NET MVC Framework" by Steven Sanderson
        // Apress publishing
        //  
        // Modified for mesoBoard

        public static string Captcha(this HtmlHelper html, string name)
        {
            string ImgFormat = "<img src=\"{0}\" alt=\"Captcha\" class='captcha' />";
            string challengeGuid = Guid.NewGuid().ToString();

            html.ViewContext.HttpContext.Session[@"__mvcbb_ddd234@SDF" + challengeGuid] = MakeRandomSolution();

            var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
            string url = urlHelper.Action("Render", "Captcha", new { challengeGuid });
            return string.Format(ImgFormat, url) + "<input type='hidden' value='" + challengeGuid + "' name='" + name + "' />";
        }

        public static string FileTypeImage(this HtmlHelper html, string fileExtension)
        {
            mbEntities db = new mbEntities();
            FileTypeRepository FileTypes = new FileTypeRepository(db);
            FileType type = FileTypes.First(item => item.Extension.Equals(fileExtension));
            if (type == null)
                return "";
            
            ConfigRepository ConfigRep = new ConfigRepository(db);
            TagBuilder tag = new TagBuilder("img");
            UrlHelper Url = new UrlHelper(html.ViewContext.RequestContext);
            tag.Attributes.Add("src", Url.Content("~/Images/FileTypes/" + type.Image));
            tag.Attributes.Add("alt", type.Extension);
            tag.Attributes.Add("title", type.Extension);
            return tag.ToString();
        }

        public static string ThemeFolder(this HtmlHelper html)
        {
            return html.ViewData["mbThemeFolder"].ToString();
        }

        public static string ThemeImage(this HtmlHelper html, string themeImageFileName)
        {
            return html.Image("~/Themes/"+html.ThemeFolder() + "/Images/" + themeImageFileName).ToString();
        }

        public static string ThemeImage(this HtmlHelper html, string themeImageFileName, string altText)
        {
            return html.Image("~/Themes/" + html.ThemeFolder() + "/Images/" + themeImageFileName, altText).ToString();
        }

        public static string ThemeImage(this HtmlHelper html, string themeImageFileName, object htmlAttributes)
        {
            return html.Image("~/Themes/" + html.ThemeFolder() + "/Images/" + themeImageFileName, (object)htmlAttributes).ToString();
        }

        private static string ParseThemeUrl(this HtmlHelper html, string relativeUrl)
        {
            string ThemeFolder = "~/Themes/" + html.ThemeFolder();
            if(relativeUrl[0] == '~')
                return relativeUrl = relativeUrl.Replace("~/", ThemeFolder);
            else
                return relativeUrl.Replace("{CTF}", "~/Themes/" + html.ThemeFolder());
        }

        private static string MakeRandomSolution()
        {
            Random rng = new Random();
            int length = rng.Next(5, 7);
            char[] buf = new char[length];
            for (int i = 0; i < length; i++)
                buf[i] = (char)('a' + rng.Next(26));
            return new string(buf);
        }

        public static string Label(this HtmlHelper html, string For, string InnerHTML, string Class="")
        {
            TagBuilder tag = new TagBuilder("label");
            tag.Attributes.Add("for", For);
            tag.Attributes.Add("class", Class);
            tag.InnerHtml = InnerHTML;
            return tag.ToString();
        }

        public static string ThreadImage(this HtmlHelper html, Thread TheThread, bool IsNew)
        {
            TagBuilder imgtag = new TagBuilder("img");
            UrlHelper Url = new UrlHelper(html.ViewContext.RequestContext);
            string ImageURL;
            string NewText = IsNew ? "new_" : "";

            int ThreadType = TheThread.Type;

            string AltTitleText = IsNew ? "New Post" : "No New Post";


            if (TheThread.IsLocked)
            {
                NewText = "locked_";
                AltTitleText = "Locked";
            }

            if (ThreadType == 1)
                ImageURL = "~/Themes/Default/Images/" + NewText + "thread.png";
            else if (ThreadType == 2)
                ImageURL = "~/Themes/Default/Images/" + NewText + "sticky.png";
            else
                ImageURL = "~/Themes/Default/Images/" + NewText + "announcement.png";



            imgtag.Attributes.Add("src", Url.Content(ImageURL));
            imgtag.Attributes.Add("alt", AltTitleText);
            imgtag.Attributes.Add("title", AltTitleText);
            return imgtag.ToString();
        }

        public static string UserAvatar(this HtmlHelper html, int UserID)
        {
            UserRepository UserRep = new UserRepository(new mbEntities());
            User TheUser = UserRep.Get(UserID);
            UserProfile TheProfile = TheUser.UserProfile;

            if (TheProfile.AvatarType == "None")
                return "";
            UrlHelper Url = new UrlHelper(html.ViewContext.RequestContext);

            string src;
            if (TheProfile.AvatarType == "Upload")
                src = Url.Content("~/Upload/Avatars/" + TheProfile.Avatar);
            else
                src = TheProfile.Avatar;

            if (!string.IsNullOrEmpty(TheUser.UserProfile.Avatar))
            {
                TagBuilder imgtag = new TagBuilder("img");
                imgtag.Attributes.Add("src", src);
                imgtag.Attributes.Add("alt", TheUser.Username + "'s Avatar");
                imgtag.Attributes.Add("title", TheUser.Username + "'s Avatar");
                return imgtag.ToString();
            }
            return "";
        }

        public static string ParseNavLink(this HtmlHelper html, NavigationLink link)
        {
            if(link == null) 
                return "";

            UrlHelper Url = new UrlHelper(html.ViewContext.RequestContext);
            TagBuilder linktag = new TagBuilder("a");

            if (html.ViewContext.TempData["BreadCrumb"] != null && link.Text == html.ViewContext.TempData["BreadCrumb"].ToString())
               linktag.AddCssClass("selected");
            else if (html.ViewContext.ViewData["BreadCrumb"] != null && link.Text == html.ViewContext.ViewData["BreadCrumb"].ToString())
                   linktag.AddCssClass("selected");
            else if (html.ViewContext.ViewData["TopBreadCrumb"] != null && link.Text == html.ViewContext.ViewData["TopBreadCrumb"].ToString())
               linktag.AddCssClass("selected");
           
           if (link.RouteValue != null)
               linktag.Attributes.Add("href", Url.RouteUrl(link.RouteValue));
           else
               linktag.Attributes.Add("href", Url.RouteUrl(link.RouteName));

           if (!string.IsNullOrEmpty(link.ImagePath))
           {
               TagBuilder img = new TagBuilder("img");
               img.Attributes.Add("src", Url.Content(link.ImagePath));
               img.Attributes.Add("alt", "");
               linktag.InnerHtml = img.ToString();               
           } 
               linktag.InnerHtml += link.Text;
               string TextLink = linktag.ToString();
               return TextLink;
        }

    }
}
